package application.employee.config;

import application.employee.api.EmployeeServiceInterface;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.endpoint.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import platform.config.RestConfigContext;
import platform.persistence.config.MongoConfigContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 配置
 *
 * @author roamer
 * @version V1.0
 * @date 2019-02-24 10:36
 */
@Configuration
@EnableMongoRepositories(basePackages = "application.employee.repository")
@ComponentScan(basePackages = {"application.employee"})
@Import({MongoConfigContext.class, RestConfigContext.class})
@PropertySource({"classpath:employee-service.properties"})
public class EmployeeContextConfig {

    @Autowired
    private EmployeeServiceInterface employeeService;

    @Autowired
    private JAXRSServerFactoryBean jaxrsServerFactoryBean;

    /**
     * 解析配置文件
     * <p>
     * BeanFactoryPostProcessor必须在Spring容器生命周期很早就实例化，
     * 声明为static时，Spring不会实例化所在的@Configuration类，
     * 否则将会导致所在的@Configuration类过早的实例化，
     * 而用于处理@Autowired、@Value等注解的类还未准备好。
     *
     * </p>
     *
     * @return {@code PropertySourcesPlaceholderConfigurer}
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        // 优先使用当前项目配置文件
        placeholderConfigurer.setLocalOverride(true);
        return placeholderConfigurer;
    }

    @Bean
    public Server server() {
        List<Object> endpoints = new ArrayList<>();
        endpoints.add(employeeService);
        jaxrsServerFactoryBean.setServiceBean(endpoints);
        return jaxrsServerFactoryBean.create();
    }
}
